import React, { FC, useEffect, useState, useMemo } from 'react';
import { history, useLocation } from 'umi';

import './index.less';

import { ReactComponent as IconHome } from './icon-home.svg';

const SubmenuNav = (props: any) => {
    const { appMenus } = props;
    const location = useLocation();

    const handleClick = (path: string) => {
        history.push(path);
    };

    return <>
        <div className='submenu-nav'>
            <h3 className='appName' onClick={() => handleClick(appMenus?.path)}>{appMenus?.menuName}</h3>
            <ul>
                {appMenus?.children?.map((item: any) => (
                    <li key={item.menuName} className={location.pathname.includes(item.path) ? 'active' : ''} onClick={() => handleClick(item.path)}>
                        <IconHome /><span>{item?.menuName}</span>
                        <i className='corner-top'></i>
                        <i className='corner-bottom'></i>
                    </li>
                ))}
            </ul>
        </div>
    </>
};

const SubmenuLinks = (props: { appMenus: any }) => {
    const { appMenus } = props;
    const location = useLocation();

    const handleClick = (path: string) => {
        history.push(path);
    };

    const links = useMemo(() => {
        let arr: any[] = [];

        if (appMenus?.children) {
            for (let item of appMenus?.children) {
                if (location.pathname.includes(item.path) && Array.isArray(item.children) && item.children.length > 0) {
                    arr = item.children;

                    break;
                }
            }
        }

        return arr;
    }, [location.pathname, appMenus]);

    return <>
        {links.length > 0 &&
            <div className='submenu-links'>
                <ul>
                    {links.map(item => (
                        <li key={item.menuName} className={location.pathname.includes(item.path) ? 'active' : ''} onClick={() => handleClick(item.path)}>{item.menuName}</li>
                    ))}
                </ul>
            </div>
        }
    </>
}

interface SubmenuProps {
    appMenus: any;
}

const Submenu: FC<SubmenuProps> = ({ appMenus }) => {
    return <div className="submenu">
        <SubmenuNav appMenus={appMenus} />
        <SubmenuLinks appMenus={appMenus} />
    </div>
}

export default Submenu;
